<template>
    <rx-dialog @handOk="handleSubmit"
               :oktext="$ti18('rxForm.saveBtn','保存')"
               @cancel="cancel"
               btnalign="center"
               order="bottom"
               style="height: 100%;"
    >
        <rx-layout>
            <div slot="center">
                <a-form :form="form">
                    <a-form-item style="display:none">
                        <a-input v-decorator="['id']"/>
                        <a-input v-decorator="['genType']"/>
                    </a-form-item>
                    <a-row>
                        <a-col :span="12">
                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="boentI18n('form.name','名称')">
                                <a-input :placeholder="boentI18n('form.name','名称')"
                                         @blur.native="getPinyinByName"
                                         v-decorator="['name', {rules: [{required: true, message: boentI18n('form.name','请输入名称','input')}]}]"/>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="boentI18n('form.alias','别名')">
                                <a-input :placeholder="boentI18n('form.alias','别名')"
                                         v-decorator="['alias', {rules: [
                                                {required: true, message: boentI18n('form.alias','请输入别名','input')},
                                                {pattern:/^[a-zA-Z][a-zA-Z0-9_-]*$/,message:this.boentI18n('form.str','不能以数字开头,不能包含【_-】以外的特殊字符！','input')}
                                             ]}]"/>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="12">
                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="boentI18n('form.category','分类')">
                                <rx-category-select cat-key="FORM" :isGrant="true"
                                                    v-if="isShowManageTree" :isAdmin="isManageToTree"
                                                    v-decorator="['treeId', {rules: [{required: true, message: boentI18n('form.category','请输入分类','input')}]}]"></rx-category-select>
                                <a-input v-else style="display:none;" v-decorator="['treeId']" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.primaryEnt','主实体')">
                                <rx-input-button @click="onSelectBoEnt" ref="mainEntId"
                                                 v-decorator="['boEnt', {rules: [{required: true, message: i18n('form.primaryEnt','请选择主实体','select')}]}]"></rx-input-button>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="24">
                            <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.storageDB','存储数据库')">
                                <a-checkbox @change="supportDbChange" :checked="supportDb==1">
                                    {{boentI18n('list.yes','是')}}
                                </a-checkbox>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <div class="table-operator">
                        <a-button type="primary" icon="plus" @click="addEnt">
                            {{$ti18('rxList.newBtn','新增')}}
                        </a-button>
                        <a-button type="danger" icon="delete" @click="removeEnt">
                            {{$ti18('rxList.delBtn','删除')}}
                        </a-button>
                    </div>
                    <div style="height: 450px;box-sizing: border-box;padding-bottom: 10px">
                        <rx-grid ref="table"
                                 :dataSource="fields"
                                 :allowRowSelect="true"
                                 :multiSelect="true"
                                 :showPage="false"
                                 :columns="columns"
                        >
                        <span slot="entId" slot-scope="{text,record,index,blur}">
                          <rx-input-button width="100%"
                                           :value="JSON.stringify({value:record.entId,text:record.entName})"
                                           @click="onSelectBoEntGrid(text,record,index,blur)"></rx-input-button>
                        </span>
                            <span slot="relateType" slot-scope="{text,record,index,blur}">
                          <a-select v-model="record.relateType" @blur="blur(index,'relateType',text,record)">
                            <a-select-option value="onetoone">
                                {{i18n('list.oneForone','一对一')}}
                            </a-select-option>
                            <a-select-option value="onetomany">
                                {{i18n('list.onetomany','一对多')}}
                            </a-select-option>
                          </a-select>
                        </span>
                        <span slot="fkField" slot-scope="{text,record,index,blur}">

                          <a-select allowClear v-model="record.fkField" @change="changeFkField(record)"
                                    :options="record.columnList"></a-select>
                        </span>
                        <span slot="pkField" slot-scope="{text,record,index,blur}">
                          <a-select allowClear v-model="record.pkField"
                                    :options="columnList"></a-select>
                        </span>
                        </rx-grid>
                    </div>
                    <a-row>
                        <a-col :span="24">
                            <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="$ti18('rxForm.describe','描述')">
                                <a-textarea v-decorator="['description']" :rows="4"/>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
import FormBoDefApi from '@/api/form/bo/formBoDef'
import FormBoAttrApi from "@/api/form/bo/formBoAttr";
import {BaseForm, RxDialog, RxInputButton, RxGrid, Dialog, Util} from "@lowcode/jpaas-common-lib";
import FormBoDefSunEdit from './FormBoDefSunEdit';

export default {
    name: 'FormBoDefEdit',
    mixins: [BaseForm],
    components: {
        RxInputButton,
        RxGrid,
        Util
    },
    data() {
        return {
            relateTypes: {'onetoone': '一对一', 'onetomany': '一对多'},
            supportDb: 1,
            columnList: [],
            fields: [],
            appId: this.$parent.curApp.appId,
            columns: [{
                title: this.i18n('form.entity','实体'), dataIndex: 'entId',
                allowCellEdit: false, width: 120, scopedSlots: {customRender: 'entId'}
            },
                {
                    title: this.i18n('form.relateType','关系定义'),
                    dataIndex: 'relateType',
                    width: 120,
                    allowCellEdit: false,
                    scopedSlots: {customRender: 'relateType'}
                },
                {
                    title: this.i18n('form.fkField','子实体关联键'),
                    dataIndex: 'fkField',
                    width: 120,
                    allowCellEdit: false,
                    scopedSlots: {customRender: 'fkField'}
                },
                {
                    title: this.i18n('form.pkField','主实体关联键'),
                    dataIndex: 'pkField',
                    width: 120,
                    allowCellEdit: false,
                    scopedSlots: {customRender: 'pkField'}
                },
               ],
            //主实体
            boEnt:""
        }
    },
    created() {
        this.isUserManager(this.$route.query.appId);
    },
    computed: {
        table() {
            return this.$refs.table;
        },
        mainEntId() {
            return this.$refs.mainEntId;
        }
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formBoDef",key);
        },
        boentI18n(name,text,key){
            return this.$ti18(name,text,"formBoEntity",key);
        },
        isNullI18n(name,text,key){
            return this.$ti18(name,text,"formBoDef",key)+this.$ti18('msg.isNullMsg','不能为空',"formBoDef");
        },
        getPinyinByName(){
            let name=this.form.getFieldsValue().name
            if (!name){
                return;
            }
            if (this.form && this.form.getFieldsValue().alias){
                return;
            }
            this.getPinyin(name).then(res => {
                //去除不可见的特殊符号
                if(res){
                    res=res.replace(/\u200B/g,'');
                }
                this.form.setFieldsValue({alias:res})
            })
        },
        onload_(values) {
            if (values) {
                this.supportDb = values.supportDb;
                var formBoEntity = values.formBoEntity;
                this.mainEntId.setVal(formBoEntity.id, formBoEntity.name);
                this.loadColumnList(formBoEntity.id);

                var boEntitys = formBoEntity.boEntityList;
                this.fields = boEntitys.map(item => {
                    var record = {
                        entId: item.id,
                        entName: item.name,
                        relateType: item.boRelation.type,
                        relateType_name: this.relateTypes[item.boRelation.type],
                        fkField: item.boRelation.fkField,
                        pkField: item.boRelation.pkField,
                        fkFieldName: item.boRelation.fkFieldName,
                        pkFieldName: item.boRelation.pkFieldName,
                    }
                    this.getBoEntId(item.id, record);
                    return record;
                })
            }
        },
        get(id) {
            return FormBoDefApi.getBoDef(id);
        },
        save(values,vm) {
            values.appId = this.appId;
            values.supportDb = this.supportDb;
            var val = this.mainEntId.getVal();
            //同时保存应用ID
            let appId = this.curApp.appId;
            values.formBoEntity = {id: val.value};
            values.formBoEntity["boRelation"] = {parentEntId: 0, type: 'main', appId: appId};
            var valid=true;
            values.formBoEntity.boEntityList = this.table.getData().map(item => {
                if(!item.relateType){
                    this.$message.error(this.isNullI18n('form.relateType','关系定义不能为空！'));
                    valid=false;
                    return ;
                }else if(!item.fkField){
                    this.$message.error(this.isNullI18n('form.subEnt','子实体关联键不能为空！'));
                    valid=false;
                    return ;
                }else if(!item.pkField){
                    this.$message.error(this.isNullI18n('form.primaryEnt','主实体关联键不能为空！'));
                    valid=false;
                    return ;
                }
                let boEnt = {
                    id: item.entId,
                    boRelation: {
                        parentEntId: val.value,
                        type: item.relateType,
                        fkField: item.fkField,
                        pkField: item.pkField,
                        fkFieldName: item.fkFieldName,
                        pkFieldName: item.pkFieldName,
                        appId: appId,
                    }
                };

                return boEnt;
            });
            if(!valid){
                vm.loading=false;
                return ;
            }
            return FormBoDefApi.saveBoDef(values);
        },
        supportDbChange(e) {
            if (e.target.checked) {
                this.supportDb = 1;
            } else {
                this.supportDb = 0;
            }
        },
        addEnt() {
            var mainEnt=this.mainEntId.getVal();
            if(!mainEnt || !mainEnt.value){
                this.$message.warning(this.i18n('form.primaryEnt',"请先选择主实体!",'select'));
                return;
            }
            this.table.addRow({});
        },
        removeEnt() {
            this.table.removeRows();
        },
        onSelectBoEnt(vm) {
            let self_ = this;
            Dialog.openBoEntDialog({
                curVm: this, widthHeight: ['900px', '600px']
            }, function (data) {
                vm.setVal(data.id, data.name);

                self_.loadColumnList(data.id);
            })
        },
        loadColumnList(entId){
            let self_=this;
            FormBoAttrApi.getIncludeStandAttrByEntId(entId).then(res => {
                self_.columnList = res.map(item => {
                    let name=item.name;
                    if(item.control=='rx-commonfield' || item.isPk==1){
                        name=item.fieldName;
                    }
                    return {label: item.comment, value: name,fieldName:item.fieldName}
                });

            })
        },

        //选择关联实体
        onSelectBoEntGrid(text, record, index, blur) {
            let self = this;
            Dialog.openBoEntDialog({
                curVm: this, widthHeight: ['800px', '600px']
            }, function (data) {
                var mainEnt=self.mainEntId.getVal();
                if(mainEnt.value==data.id){
                    self.$message.warning(self.i18n('msg.validSameMsg',"关联实体不允许与主实体相同!"));
                    return;
                }
                //更新
                Object.assign(record, {entId: data.id, entName: data.name});
                self.getBoEntId(data.id, record);
            })
        },
        //获取BO的字段更表
        getBoEntId(id, record) {
            FormBoAttrApi.getIncludeStandAttrByEntId(id).then(res => {
                record.columnList = res.map(item => {
                    return {label: item.comment, value: item.name,fieldName:item.fieldName}
                });
            })
        },
        changeFkField(record){
            let val=record.fkField;
            if(!val){
                record.fkFieldName="";
                return ;
            }
            let ary=record.columnList.filter(item=>{
                return item.value==val;
            });
            let row=ary[0];
            record.fkFieldName=row.fieldName;
        }

    }
}
</script>
